<template>
  <div>
    <el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>申请管理</el-breadcrumb-item>
      <el-breadcrumb-item>调宿申请</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin: 15px; min-height: calc(100vh - 111px)">
      <div>
        <!--    功能区-->
        <div style="margin: 10px 0">
          <!--    搜索区-->
          <div style="margin: 10px 0">
            <el-input
              v-model="search"
              clearable
              placeholder="请输入学号"
              prefix-icon="Search"
              style="width: 20%"
            />
            <el-button
              icon="Search"
              style="margin-left: 5px"
              type="primary"
              @click="load"
            ></el-button>
            <div style="float: right">
              <el-tooltip content="添加" placement="top">
                <el-button
                  icon="plus"
                  style="width: 50px"
                  type="primary"
                  @click="add"
                ></el-button>
              </el-tooltip>
            </div>
          </div>
        </div>
        <!--    表格-->
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          max-height="705"
          style="width: 100%"
        >
          <el-table-column label="#" type="index" />
          <el-table-column
            label="学号"
            prop="username"
            sortable
            width="100px"
          />
          <el-table-column label="姓名" prop="name" width="100px" />
          <el-table-column label="当前房间号" prop="currentRoomId" sortable />
          <el-table-column label="当前床位号" prop="currentBedId" sortable />
          <el-table-column label="目标房间号" prop="towardsRoomId" sortable />
          <el-table-column label="目标床位号" prop="towardsBedId" sortable />
          <el-table-column
            :filter-method="filterTag"
            :filters="[
              { text: '未处理', value: '未处理' },
              { text: '通过', value: '通过' },
              { text: '驳回', value: '驳回' },
            ]"
            filter-placement="bottom-end"
            label="申请状态"
            prop="state"
            sortable
            width="130px"
          >
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.state === '通过'
                    ? 'success'
                    : scope.row.state === '驳回'
                    ? 'danger'
                    : 'info'
                "
                disable-transitions
                >{{ scope.row.state }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="申请时间" prop="applyTime" sortable />
          <el-table-column label="处理时间" prop="finishTime" sortable />
          <!--      操作栏-->
          <el-table-column label="操作" width="130px">
            <template #default="scope">
              <el-button
                icon="more-filled"
                type="default"
                @click="showDetail(scope.row)"
              ></el-button>
              <el-button
                v-if="scope.row.state !== '通过'"
                icon="Edit"
                type="primary"
                @click="handleEdit(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div style="margin: 10px 0">
          <el-pagination
            v-model:currentPage="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
        <div>
          <!--      弹窗-->
          <el-dialog
            v-model="dialogVisible"
            title="操作"
            width="30%"
            @close="cancel"
          >
            <el-form
              ref="form"
              :model="form"
              :rules="rules"
              label-width="120px"
            >
              <el-form-item label="学号" prop="username">
                <el-input
                  v-model="form.username"
                  disabled
                  style="width: 80%"
                ></el-input>
              </el-form-item>
              <el-form-item label="姓名" prop="name">
                <el-input
                  v-model="form.name"
                  disabled
                  style="width: 80%"
                ></el-input>
              </el-form-item>
              <el-form-item disabled label="当前房间号" prop="currentRoomId">
                <el-input
                  v-model="form.currentRoomId"
                  disabled
                  style="width: 80%"
                ></el-input>
              </el-form-item>
              <el-form-item label="当前床位号" prop="currentBedId">
                <el-input
                  v-model="form.currentBedId"
             
                  style="width: 80%"
                ></el-input>
              </el-form-item>
              <el-form-item label="目标房间号" prop="towardsRoomId">
                <el-input
                  v-model.number="form.towardsRoomId"
                  style="width: 80%"
                ></el-input>
              </el-form-item>
              <el-form-item label="目标床位号" prop="towardsBedId">
                <el-input
                  v-model.number="form.towardsBedId"
                  style="width: 80%"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="申请时间"
                prop="applyTime"
                style="margin-top: 27px"
              >
                <el-date-picker
                  v-model="form.applyTime"
                  :disabled="!judgeOption"
                  clearable
                  placeholder="选择时间"
                  style="width: 50%"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                ></el-date-picker>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
              </span>
            </template>
          </el-dialog>
          <!--详情信息弹窗-->
          <el-dialog
            v-model="detailDialog"
            title="学生信息"
            width="30%"
            @close="cancel"
          >
            <el-form ref="form" :model="form" label-width="220px">
              <el-form-item label="学号：" prop="username">
                <template #default="scope">
                  <span>{{ form.username }}</span>
                </template>
              </el-form-item>
              <el-form-item label="姓名：" prop="name">
                <template #default="scope">
                  <span>{{ form.name }}</span>
                </template>
              </el-form-item>
              <el-form-item label="当前房间号：" prop="currentRoomId">
                <template #default="scope">
                  <span>{{ form.currentRoomId }}</span>
                </template>
              </el-form-item>
              <el-form-item label="当前床位号：" prop="currentBedId">
                <template #default="scope">
                  <span>{{ form.currentBedId }}</span>
                </template>
              </el-form-item>
              <el-form-item label="目标房间号：" prop="towardsRoomId">
                <template #default="scope">
                  <span>{{ form.towardsRoomId }}</span>
                </template>
              </el-form-item>
              <el-form-item label="目标床位号：" prop="towardsBedId">
                <template #default="scope">
                  <span>{{ form.towardsBedId }}</span>
                </template>
              </el-form-item>
              <el-form-item label="申请时间：" prop="applyTime">
                <template #default="scope">
                  <span>{{ form.applyTime }}</span>
                </template>
              </el-form-item>
              <el-form-item label="申请状态：" prop="state">
                <template #default="scope">
                  <span>{{ form.state }}</span>
                </template>
              </el-form-item>
              <el-form-item label="处理时间：" prop="finishTime">
                <template #default="scope">
                  <span>{{ form.finishTime }}</span>
                </template>
              </el-form-item>
            </el-form>
          </el-dialog>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script >
import request from "@/utils/request";

const { ElMessage } = require("element-plus");
export default {
  name: "AdjustRoomInfo",
  data() {
    const checkRoomState = (rule, value, callback) => {
      this.dormRoomId = value;
      if (typeof value === "number") {
        request.get("/room/checkRoomState/" + value).then((res) => {
          request.get("/room/checkRoomExist/" + value).then((result) => {
            if (result.code === "-1") {
              callback(new Error(result.msg));
            }
            if (res.code === "-1") {
              callback(new Error(res.msg));
            }
            callback();
          });
        });
      } else {
        callback(new Error("请输入正确的数据"));
      }
    };
    const checkBedState = (rule, value, callback) => {
      request
        .get("/room/checkBedState/" + this.dormRoomId + "/" + value)
        .then((res) => {
          if (res.code === "0") {
            callback();
          } else {
            callback(new Error(res.msg));
          }
        });
    };
    return {
      loading: true,
      dialogVisible: false,
      detailDialog: false,
      search: "",
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      form: {},
      dormRoomId: 0,
      orderState: false,
      judgeOption: false,
      rules: {
        username: [
          { required: true, message: "请输入学号", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9]{4,9}$/,
            message: "必须由 2 到 5 个字母或数字组成",
            trigger: "blur",
          },
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            pattern: /^(?:[\u4E00-\u9FA5·]{2,10})$/,
            message: "必须由 2 到 10 个汉字组成",
            trigger: "blur",
          },
        ],
        currentRoomId: [
          { required: true, message: "请输入当前房间号", trigger: "blur" },
        ],
        currentBedId: [
          { required: true, message: "请输入当前床位号", trigger: "blur" },
        ],
        towardsRoomId: [{ validator: checkRoomState, trigger: "blur" }],
        towardsBedId: [{ validator: checkBedState, trigger: "blur" }],
      },
    };
  },
  created() {
    this.loadByUsername();
    this.loading = true;
    setTimeout(() => {
      //设置延迟执行
      this.loading = false;
    }, 1000);
  },
  methods: {
    async loadByUsername() {
      const currentUser = JSON.parse(sessionStorage.getItem("user")); // 获取当前登录用户信息
      const username = currentUser.username; // 假设用户信息中包含 username
      request
        .get("/adjustRoom/findByUsername", {
          params: {
            username: username, // 传递用户名参数
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            search: this.search,
          },
        })
        .then((res) => {
          this.tableData = res.data.records;
          this.total = res.data.total;
          this.loading = false;
        });
    },

    filterTag(value, row) {
      return row.gender === value;
    },
    add() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
        this.form.username = JSON.parse(
          sessionStorage.getItem("user")
        ).username;
        this.form.name = JSON.parse(sessionStorage.getItem("user")).name;
        request.get("/room/getMyRoom/" + this.form.username).then((res) => {
          this.form.currentRoomId = res.data.dormRoomId;
          this.form.currentBedId = this.calBedNum(this.form.username, res.data);
        });
        this.judgeOption = true;
      });
    },
    calBedNum(username, data) {
      if (data.firstBed === username) {
        return 1;
      } else if (data.secondBed === username) {
        return 2;
      } else if (data.thirdBed === username) {
        return 3;
      } else if (data.fourthBed === username) {
        return 4;
      }
    },
    judgeOrderState(state) {
      if (state === "通过") {
        this.orderState = true;
      } else if (state === "驳回") {
        this.orderState = false;
      } else if (state === "未处理") {
        this.orderState = false;
      }
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.judgeOption === false) {
            //修改
            this.judgeOrderState(this.form.state);
            request
              .put("/adjustRoom/update/" + this.orderState, this.form)
              .then((res) => {
                if (res.code === "0") {
                  ElMessage({
                    message: "修改成功",
                    type: "success",
                  });
                  this.search = "";
                  this.load();
                  this.dialogVisible = false;
                } else if (res.msg === "重复操作") {
                  ElMessage({
                    message: res.msg,
                    type: "error",
                  });
                  this.search = "";
                  this.load();
                  this.dialogVisible = false;
                } else {
                  ElMessage({
                    message: res.msg,
                    type: "error",
                  });
                }
              });
          } else if (this.judgeOption === true) {
            //添加
            request.post("/adjustRoom/add", this.form).then((res) => {
              if (res.code === "0") {
                ElMessage({
                  message: "添加成功",
                  type: "success",
                });
                this.search = "";
                this.load();
                this.dialogVisible = false;
              } else {
                ElMessage({
                  message: res.msg,
                  type: "error",
                });
              }
            });
          }
        }
      });
    },
    cancel() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
      this.detailDialog = false;
    },
    showDetail(row) {
      // 查看详情
      this.detailDialog = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
        this.form = JSON.parse(JSON.stringify(row));
      });
    },
    handleEdit(row) {
      //修改
      // 生拷贝
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
        this.form = JSON.parse(JSON.stringify(row));
        this.judgeOption = false;
      });
    },
    handleSizeChange(pageSize) {
      //改变每页个数
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      //改变页码
      this.currentPage = pageNum;
      this.load();
    },
  },
};
</script>
